<?php
// File: app/controllers/users_controller.php	
	class MUsersController extends AppController{

		var $name = 'MUser';
		var $helpers = array ('Html','Form','Javascript','Paginator','Csv');
		var $components = array('Session');
		
		function login()
		{
			$this->layout = 'login_UI';
			$this->set('title_for_layout','Avoidance Words System');
				
			$active = $this->Auth->user();
			if($active['MUser']['invalid_flg'] == 1){
				$this->redirect($this->Auth->logout());
			}
		}

		function logout(){
			$this->redirect($this->Auth->logout());
		}
		
		function index()
		{
			$this->set('title_for_layout','Users List');
			
			$this->paginate=array
			(
				'limit' => 10,
				'order' => array('id' => 'desc'),
				'conditions' => array('invalid_flg' => '0')
			);
			$data = $this->paginate("MUser");
			$this->set("usersinfo",$data);
		}
		
		function personal_detail($id=null)
		{
			$this->set('title_for_layout','Personal Details');
			$this->MUser->id = $id;
			$this->set('m_user', $this->MUser->read());
			
			$Authid = $this->Auth->user();
			if($Authid['MUser']['id'] != $id){
				$this->redirect(array('controller'=>'m_users','action'=>'index'));
				$this->Session->setFlash('Sorry you can not see another one details', true);
			}
		}
		
		function user_detail($id=null)
		{
			$this->set('title_for_layout','User Details');
			$this->MUser->id = $id;
			$this->set('m_user', $this->MUser->read());
				
			$Authid = $this->Auth->user();
		}
		
		function add() {
			$this->set('title_for_layout','Add New User');
	
			if (!empty($this->data)) {
				if(isset($_POST['create'])){
					if($this->MUser->check_add()==true){
						if (isset($this->data[$this->name]['newPassword']) && !empty($this->data[$this->name]['newPassword']))
						{
							$this->data['MUser']['password'] = Security::hash($this->data[$this->name]['newPassword'], 'MD5', true);
							//debug($this->MUser->password);
						}
						
						if ($this->MUser->save($this->data)) {
							//debug($this->data);
							$this->Session->setFlash('Your user has been saved.');
							$this->redirect(array('action' => 'index'));
						}
					}
					else
					{
    					$this->Session->setFlash('Error in some fields, please check again');
					}
				}
			}
		}
		
		function ajax_check_user_id() {
			$this->layout = 'ajax';
			if (!empty($this->data)) {
				if ($this->data['MUser']['user_id'] == '') {
					$this->set('value', 0);
				} else {
					$SQL = "SELECT user_id FROM m_users WHERE user_id = '".$this->data['MUser']['user_id']."'";
					$u = $this->MUser->query($SQL);
					if (empty($u)) {
						$this->set('value', 1);
					} else {
						$this->set('value', 0);
					}
				}
			} else {
				$this->set('value', 0);
			}
		}
		
		function ajax_check_email_address() {
			$this->layout = 'ajax';
			if (!empty($this->data)) {
				if ($this->data['MUser']['email_address'] == '') {
					$this->set('value', 0);
				} else {
					$SQL = "SELECT email_address FROM m_users WHERE email_address = '".$this->data['MUser']['email_address']."'";
					$u = $this->MUser->query($SQL);
					if (empty($u)) {
						$this->set('value', 1);
					} else {
						$this->set('value', 0);
					}
				}
			} else {
				$this->set('value', 0);
			}
		}
		
		function edit($id) {
			$this->set('title_for_layout','Edit User');			
			if($this->MUser->check_add()==true){
				if (empty($this->data)) 
				{
					$this->data = $this->MUser->read(null, $id);
				} 
				else 
				{
					$this->MUser->set($this->data);
					if($this->MUser->check_edit()==true){	
						if ($this->MUser->save($this->data)) {
							$this->Session->setFlash('Your user has been updated.');
							$this->redirect(array('action' => 'index'));
						}
					}
				}
			}
		}
		
		function delete($id) {
			$this->MUser->id = $id;
			if ($this->MUser->saveField('invalid_flg',1))
			{
				$this->Session->setFlash('The user with id: ' .$id . ' has been deleted.');
				$this->redirect(array('action' => 'index'));
			}
		}
		
		
		function change_pass()
		{
			$this->set('title_for_layout','Change Pass');
			$AuthArr=$this->Auth->user();
			$id = $AuthArr['MUser']['id'];
		
			if(!empty($this->data))
			{
				$old = $this->data['MUser']['old_password'];
				$old_password = $this->Auth->password($old);
				$check_password = $this->MUser->find('first',array('conditions'=>array('MUser.id'=>$id,'MUser.password'=>$old_password),'fields'=>array('MUser.password')));
				$new_pass_gen = $this->data['MUser']['new_password'];
				$new_pass = $this->Auth->password($new_pass_gen);
		
				if(!empty($check_password))
				{
					$new = $this->data['MUser']['new_password'];
		
					$re_type_new = $this->data['MUser']['re_new_password'];
		
					if(!empty($new) && !empty($re_type_new))
					{
						if($new == $re_type_new)
						{
							//$this->data['MUser']['password']= $new_pass;
							$this->MUser->id = $id;
		
							if($this->MUser->saveField('password',$new_pass))
							{
								$this->Session->setFlash(__('You change password successfully', true));
								$this->redirect(array('controller'=>'m_users','action'=>'personal_detail',$id));
							}
							else
							{
								$this->Session->setFlash(__('It had some problem, please try again', true));
							}
						}
						else
						{
							$this->Session->setFlash(__('Two passwords are not matched', true));
						}		
					}
					else 
					{
						$this->Session->setFlash(__('Please fill up new password and repeat password', true));
					}
				}
				else
				{
					$this->Session->setFlash(__('Sorry your current password is incorrect', true));
				}
			}
		
		}
		
		function edit_pass($id)
		{
			$this->set('title_for_layout','Edit Password User');
			if (empty($this->data))
			{
				$this->data = $this->MUser->read(null, $id);
			}
			else
			{
				if (!empty($this->data))
				{
					$new = $this->data['MUser']['new_password'];
					$re_type_new = $this->data['MUser']['re_new_password'];
					$new_pass = $this->Auth->password($new);
					
					if(!empty($new) && !empty($re_type_new))
					{
						if($new == $re_type_new)
						{
							$this->MUser->id = $id;
							$this->MUser->set($this->data);
							if($this->MUser->saveField('password',$new_pass))
							{
								$this->Session->setFlash(__('You change password successfully', true));
								$this->redirect(array('controller'=>'m_users','action'=>'edit',$id));
							}
							else
							{
								$this->Session->setFlash(__('It had some problem, please try again', true));
							}
						}
					}
					else
					{
						$this->Session->setFlash(__('Two passwords are not matched', true));
					}
				}
				else
				{
					$this->Session->setFlash(__('Please fill up new password and repeat password', true));
				}
			}
		}
		
		
		function search() {
				
			// The page we will redirect to
			$url['action'] = 'result';
			foreach ($this->data as $k=>$v){
				foreach ($v as $kk=>$vv){
					$url[$k.'.'.$kk]=$vv;
				}
			}
			// Redirect the user to the url
			$this->redirect($url, null, true);
		}
		
		function result(){
			$this->set('title_for_layout','Search Users');
			$conditions = array();
			$data = array();
			if(!empty($this->passedArgs)){
				//Fillter users
				if(isset($this->passedArgs['MUser.user_id'])) {
					$keywords = $this->passedArgs['MUser.user_id'];
					$conditions[] = array(
			    						"OR" => array(
			    								'MUser.user_id LIKE' => "%$keywords%",
					)
					);
					$data['MUser']['user_id'] = $keywords;
				}
				//Fillter username
				if(isset($this->passedArgs['MUser.user_name'])) {
					$keywords = $this->passedArgs['MUser.user_name'];
					$conditions[] = array(
			                        "OR" => array(
			                                    'MUser.user_name LIKE' => "%$keywords%",
			                                    'MUser.user_name_kata LIKE' => "%$keywords%" 
					)
					);
					$data['MUser']['user_name'] = $keywords;
				}
				//Limit and Order By
				$this->paginate= array(
			                    'limit' => 4,
			                    'order' => array('id' => 'desc'),
				);
			  
				$this->data = $data;
				$this->set("searchresults",$this->paginate("MUser",$conditions));
			}
		}
		
		function csv_export() {
			$this->set('title_for_layout','Export Users List');
			Configure::write('debug', 0);
			$this->layout = false;
			$filename = 'Userlist_'.date('YmdHis');//DO NOT change this, the validation in Import will be error 
			$th = array('id','user_id','user_name','user_name_kata','password','email_address','creator','create_time','updator','update_time','invalid_flg');
			$Th_name  = array('ID','User ID','Username','Username Kata','Password','Email Address','Creator','Create Time','Updator','Update Time','Invalid Flag');
			$td = $this->MUser->find('all', array('fields' => $th));
			$this->set(compact('filename', 'Th_name', 'td'));
		}
		
		function csv_import(){
			$this->set('title_for_layout','Import Words List');
			
			//Get current username.
			$get_author_infor = $this->Auth->user();
			$author=$get_author_infor['MUser']['user_name'];
			
			if (!empty($this->data)) {
				$up_file = $this->data['MUser']['file_name']['tmp_name'];
				$fileName = TMP.'/csv/'.$this->data['MUser']['file_name']['name'];
				if (is_uploaded_file($up_file)){
					move_uploaded_file($up_file, $fileName);
					try {
						 
						$csvData = file($fileName, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
						foreach($csvData as $key => $line){
							if($key != 0) {
								$record = split(",", $line);
								mb_language("Japanese");
								if(empty($record[6])){$creator=$author;}else{$creator=$record[6];}
								if(empty($record[7])){$create_time=date('Y-m-d H:i:s');}else{$create_time=$record[7];}
								if(empty($record[10])){$invalid_flg=0;}else{$invalid_flg=$record[10];}
								if(empty($record[4])){$pass='89a94f49d32fb1308adaca2182368689';}else{$pass=$record[4];}
								
								$data = array(
	                                'id' => $record[0],
	                                'user_id' => mb_convert_encoding($record[1], "UTF-8", "SHIFT_JIS"),
	                                'user_name' => mb_convert_encoding($record[2], "UTF-8", "SHIFT_JIS"),
	    							'user_name_kata' => mb_convert_encoding($record[3], "UTF-8", "SHIFT_JIS"),
									'password' => $pass,
	    							'email_address' => mb_convert_encoding($record[5], "UTF-8", "SHIFT_JIS"),
	    							'creator' => mb_convert_encoding($creator, "UTF-8", "SHIFT_JIS"),
	    							'create_time' => $create_time,
	    							'updator' => mb_convert_encoding($record[8], "UTF-8", "SHIFT_JIS"),
	    							'update_time' => $record[9],
	    							'invalid_flg' => $invalid_flg
								);
								$this->MUser->create($data);
								if ($this->MUser->save()) {
									$this->Session->setFlash('Import to me was successful');
								} else {
									$this->Session->setFlash('Import to me failed');
								}
							}
						}
					} catch(Exception $e) {
						$this->MUser->rollback();
					}
				}
			}
			
		}
		
	}/*** End Class ***/
?>